<template>
  <div class="shenchan-info-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>生产信息管理</h2>
    </div>

    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">{{ statistics.totalRecords || 0 }}</div>
              <div class="stat-label">总记录数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">{{ statistics.totalProductCount || 0 }}</div>
              <div class="stat-label">总产品数量</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">{{ statistics.productVarieties || 0 }}</div>
              <div class="stat-label">产品种类</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">{{ statistics.averageProductCount || 0 }}</div>
              <div class="stat-label">平均产量</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增生产信息
      </el-button>
      <!-- <el-button type="danger" :disabled="!hasSelectedItems" @click="handleBatchDelete">
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button> -->
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" class="search-form">
        <el-form-item label="产品名称">
          <el-input v-model="searchForm.productName" placeholder="请输入产品名称" clearable />
        </el-form-item>
        <el-form-item label="工序路线名称">
          <el-select 
            v-model="searchForm.processrouteId" 
            placeholder="请选择工序路线名称"
            clearable
            filterable
            style="width: 200px"
            @focus="loadProcessroutes"
          >
            <el-option 
              v-for="item in processrouteList" 
              :key="item.id" 
              :label="item.processrouteName" 
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleResetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        border
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
        
        <el-table-column label="序列号SID" width="120">
          <template #default="scope">
            {{ scope.row.sid || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="物料编号" width="150">
          <template #default="scope">
            {{ scope.row.productMaterial?.productcode || scope.row.productcode || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="工序路线名称" min-width="150">
          <template #default="scope">
            {{ scope.row.processroute?.processrouteName || scope.row.processrouteName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="产品名称" min-width="150">
          <template #default="scope">
            {{ scope.row.productName || scope.row.ProductName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="规格" min-width="120">
          <template #default="scope">
            {{ scope.row.productStandard || scope.row.ProductStandard || scope.row.specifications || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="产品数量" width="120">
          <template #default="scope">
            {{ scope.row.productCount || scope.row.ProductCount || scope.row.count || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="产品颜色" width="120">
          <template #default="scope">
            {{ scope.row.productColor || scope.row.ProductColor || scope.row.color || '-' }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">检验</el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogMode === 'add' ? '新增生产信息' : '编辑生产信息'"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="序列号SID" prop="sid">
              <el-input 
                v-model="formData.sid" 
                placeholder="请点击生成序列号SID"
                @click="handleSidClick"
                readonly
                style="cursor: pointer"
              >
                <template #suffix>
                  <el-icon><Setting /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料编号" prop="productcode">
              <el-select 
                v-model="formData.productcode" 
                placeholder="请选择物料编号"
                style="width: 100%"
                filterable
                @focus="loadProductMaterials"
              >
                <el-option 
                  v-for="item in productMaterialList" 
                  :key="item.productcode" 
                  :label="item.productcode" 
                  :value="item.productcode"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工序路线名称" prop="processrouteName">
              <el-select 
                v-model="formData.processrouteName" 
                placeholder="请选择工序路线名称"
                style="width: 100%"
                filterable
                @focus="loadProcessroutes"
              >
                <el-option 
                  v-for="item in processrouteList" 
                  :key="item.processrouteName" 
                  :label="item.processrouteName" 
                  :value="item.processrouteName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="formData.productName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格" prop="productStandard">
              <el-input v-model="formData.productStandard" placeholder="请输入产品规格" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品数量" prop="productCount">
              <el-input-number v-model="formData.productCount" :min="0" style="width: 100%" placeholder="请输入产品数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品颜色" prop="productColor">
              <el-input v-model="formData.productColor" placeholder="请输入产品颜色" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="生产信息详情"
      width="600px"
    >
      <div v-if="viewData" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="生产信息ID">{{ viewData.id }}</el-descriptions-item>
          <el-descriptions-item label="序列号SID">{{ viewData.sid }}</el-descriptions-item>
          <el-descriptions-item label="物料编号">{{ viewData.productcode }}</el-descriptions-item>
          <el-descriptions-item label="工序路线名称">{{ viewData.processrouteName }}</el-descriptions-item>
          <el-descriptions-item label="产品名称">{{ viewData.productName }}</el-descriptions-item>
          <el-descriptions-item label="规格">{{ viewData.productStandard }}</el-descriptions-item>
          <el-descriptions-item label="产品数量">{{ viewData.productCount }}</el-descriptions-item>
          <el-descriptions-item label="产品颜色">{{ viewData.productColor }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 如果有工序信息，显示工序详情 -->
        <div v-if="viewData.processroute" class="process-info" style="margin-top: 20px;">
          <h4>工序路线信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="工序路线ID">{{ viewData.processroute.id }}</el-descriptions-item>
            <el-descriptions-item label="工序路线名称">{{ viewData.processroute.processrouteName }}</el-descriptions-item>
            <el-descriptions-item label="工序路线类型">{{ viewData.processroute.processrouteType }}</el-descriptions-item>
            <el-descriptions-item label="工序路线状态">{{ viewData.processroute.processrouteState ? '启用' : '禁用' }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>

    <!-- 序列号SID编码规则生成对话框 -->
    <el-dialog
      v-model="sidCodeRuleDialogVisible"
      title="单据编码(新建)"
      width="800px"
      @close="resetSidCodeRuleForm"
    >
      <el-form
        ref="sidCodeRuleFormRef"
        :model="sidCodeRuleFormData"
        :rules="sidCodeRuleFormRules"
        label-width="120px"
        class="code-rule-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="业务名称" prop="businessName">
              <el-select 
                v-model="sidCodeRuleFormData.businessName" 
                placeholder="请选择业务名称"
                style="width: 100%"
              >
                <el-option label="生产信息" value="生产信息" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规则名称" prop="ruleName">
              <el-input v-model="sidCodeRuleFormData.ruleName" placeholder="请输入规则名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单据字段" prop="documentField">
              <el-select 
                v-model="sidCodeRuleFormData.documentField" 
                placeholder="请选择单据字段"
                style="width: 100%"
              >
                <el-option label="序列号SID" value="序列号SID" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="日期排序字段" prop="dateField">
              <el-select 
                v-model="sidCodeRuleFormData.dateField" 
                placeholder="请选择日期字段"
                style="width: 100%"
              >
                <el-option label="注册时间" value="注册时间" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="前缀" prop="prefix">
              <el-input v-model="sidCodeRuleFormData.prefix" placeholder="请输入前缀" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规则类型" prop="ruleType">
              <el-select 
                v-model="sidCodeRuleFormData.ruleType" 
                placeholder="请选择规则类型"
                style="width: 100%"
              >
                <el-option label="年月日" value="年月日" />
                <el-option label="年月" value="年月" />
                <el-option label="年" value="年" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="编号位数" prop="numberLength">
              <el-input-number 
                v-model="sidCodeRuleFormData.numberLength" 
                :min="1" 
                :max="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="增长类型" prop="incrementType">
              <el-select 
                v-model="sidCodeRuleFormData.incrementType" 
                placeholder="请选择增长类型"
                style="width: 100%"
              >
                <el-option label="编号每日从1开始自增" value="编号每日从1开始自增" />
                <el-option label="编号连续自增" value="编号连续自增" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="连接符号" prop="connector">
          <el-input 
            v-model="sidCodeRuleFormData.connector" 
            placeholder="请输入连接符号"
            style="width: 200px"
          />
        </el-form-item>

        <div class="code-preview-section">
          <h4>编码预览</h4>
          <div class="preview-code">
            {{ generateSidPreviewCode() }}
          </div>
        </div>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="sidCodeRuleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSidCodeRuleSubmit">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Search, Refresh, Setting } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ShenchanInfoAPI } from '@/Http/http'

// 路由实例
const router = useRouter()

// 接口类型定义
interface ShenchanInfo {
  id?: string
  sid?: string
  productcode?: string
  processrouteName?: string
  productName: string
  productStandard: string
  productCount: number
  productColor: string
  processroute?: any
  productMaterial?: any
  // 兼容不同的字段名
  ProductName?: string
  ProductStandard?: string
  specifications?: string
  ProductCount?: number
  count?: number
  ProductColor?: string
  color?: string
}

interface Statistics {
  totalRecords: number
  totalProductCount: number
  productVarieties: number
  averageProductCount: number
}

// 响应式数据
const loading = ref(false)
const tableData = ref<ShenchanInfo[]>([])
const selectedItems = ref<ShenchanInfo[]>([])
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit'>('add')
const formRef = ref()
const viewData = ref<ShenchanInfo | null>(null)

// 下拉框数据源
const productMaterialList = ref<any[]>([])
const processrouteList = ref<any[]>([])

// 序列号SID编码规则生成对话框相关
const sidCodeRuleDialogVisible = ref(false)
const sidCodeRuleFormRef = ref()
const sidCodeRuleFormData = reactive({
  businessName: '生产信息',
  ruleName: '生产管理',
  documentField: '序列号SID',
  dateField: '注册时间',
  prefix: 'SC',
  ruleType: '年月日',
  numberLength: 5,
  incrementType: '编号每日从1开始自增',
  connector: ''
})

// 统计数据
const statistics = ref<Statistics>({
  totalRecords: 0,
  totalProductCount: 0,
  productVarieties: 0,
  averageProductCount: 0
})

// 搜索表单
const searchForm = reactive({
  productName: '',
  processrouteId: '' as string | number
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 表单数据
const formData = reactive<ShenchanInfo>({
  id: '',
  sid: '',
  productcode: '',
  processrouteName: '',
  productName: '',
  productStandard: '',
  productCount: 0,
  productColor: ''
})

// 表单验证规则
const formRules = {
  sid: [
    { required: true, message: '请输入序列号SID', trigger: 'blur' }
  ],
  productcode: [
    { required: true, message: '请输入物料编号', trigger: 'blur' }
  ],
  processrouteName: [
    { required: true, message: '请输入工序路线名称', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '请输入产品名称', trigger: 'blur' }
  ],
  productStandard: [
    { required: true, message: '请输入产品规格', trigger: 'blur' }
  ],
  productCount: [
    { required: true, message: '请输入产品数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '产品数量不能小于0', trigger: 'blur' }
  ],
  productColor: [
    { required: true, message: '请输入产品颜色', trigger: 'blur' }
  ]
}

// 序列号SID编码规则表单验证规则
const sidCodeRuleFormRules = {
  businessName: [
    { required: true, message: '请选择业务名称', trigger: 'change' }
  ],
  ruleName: [
    { required: true, message: '请输入规则名称', trigger: 'blur' }
  ],
  documentField: [
    { required: true, message: '请选择单据字段', trigger: 'change' }
  ],
  dateField: [
    { required: true, message: '请选择日期字段', trigger: 'change' }
  ],
  prefix: [
    { required: true, message: '请输入前缀', trigger: 'blur' }
  ],
  ruleType: [
    { required: true, message: '请选择规则类型', trigger: 'change' }
  ],
  numberLength: [
    { required: true, message: '请输入编号位数', trigger: 'blur' }
  ],
  incrementType: [
    { required: true, message: '请选择增长类型', trigger: 'change' }
  ]
}

// 计算属性
const hasSelectedItems = computed(() => selectedItems.value.length > 0)

// 获取生产信息列表
const fetchShenchanInfoList = async () => {
  loading.value = true
  try {
        // 构建查询参数
        const params: any = {
          id: "0",
          processrouteId: 0,
          productName: "",
          productColor: "",
          productStandard: "",
          maxCount: 0,
          pageIndex: pagination.currentPage - 1,
          pageSize: pagination.pageSize
        }
        
        // 根据搜索条件设置参数
        if (searchForm.processrouteId && searchForm.processrouteId !== '') {
          params.processrouteId = Number(searchForm.processrouteId)
        }
        
        if (searchForm.productName && searchForm.productName.trim() !== '') {
          params.productName = searchForm.productName.trim()
        }
    
    const response = await ShenchanInfoAPI.post('/api/ShenchanInfo/QueryShenchanInfoList', params)
    
    // 添加调试信息
    // console.log('🔍 查询参数:', params)
    // console.log('📊 API响应:', response.data)
    // console.log('🔍 搜索表单数据:', searchForm)
    
    if (response.data.code === 100) {
      const data = response.data.data
      // console.log('📋 返回数据结构:', data)
      
      // 根据实际API返回结构调整数据处理
      if (Array.isArray(data)) {
        tableData.value = data
        pagination.total = data.length
        // console.log('✅ 数据格式: 直接数组，条数:', data.length)
      } else if (data && data.data) {
        tableData.value = data.data || []
        pagination.total = data.total || 0
        // console.log('✅ 数据格式: 分页对象，条数:', data.data?.length)
      } else {
        tableData.value = data ? [data] : []
        pagination.total = tableData.value.length
        // console.log('✅ 数据格式: 单个对象或空')
      }
      
        // 更新统计信息
        updateStatistics()
      } else {
        // console.error('API返回错误:', response.data)
        ElMessage.error(response.data.msg || '获取数据失败')
        
        // 如果API查询失败，尝试本地搜索
        // console.log('🔍 API查询失败，尝试本地搜索')
        performLocalSearch()
      }
    } catch (error) {
      console.error('获取生产信息列表失败:', error)
      ElMessage.error('获取数据失败，请检查网络连接')
      
      // 如果网络错误，也尝试本地搜索
      // console.log('🔍 网络错误，尝试本地搜索')
      performLocalSearch()
    } finally {
      loading.value = false
    }
  }

// 存储所有数据的备份，用于本地搜索
const allTableData = ref<ShenchanInfo[]>([])

// 获取所有数据（不带搜索条件）
const fetchAllData = async () => {
  try {
    const params = {
      id: "0",
      processrouteId: 0,
      productName: "",
      productColor: "",
      productStandard: "",
      maxCount: 0,
      pageIndex: 0,
      pageSize: 1000 // 获取更多数据
    }
    
    const response = await ShenchanInfoAPI.post('/api/ShenchanInfo/QueryShenchanInfoList', params)
    
    if (response.data.code === 100) {
      const data = response.data.data
      if (Array.isArray(data)) {
        allTableData.value = data
      } else if (data && data.data) {
        allTableData.value = data.data || []
      } else {
        allTableData.value = data ? [data] : []
      }
      // console.log('📦 获取到所有数据:', allTableData.value.length, '条')
    }
  } catch (error) {
    // console.error('获取所有数据失败:', error)
  }
}

// 本地搜索功能
const performLocalSearch = () => {
  // console.log('🔍 执行本地搜索')
  
  if (allTableData.value.length === 0) {
    // console.log('🔍 没有本地数据，先获取所有数据')
    fetchAllData().then(() => {
      if (allTableData.value.length > 0) {
        filterLocalData()
      } else {
        ElMessage.warning('无法获取数据进行搜索')
      }
    })
    return
  }
  
  filterLocalData()
}

// 过滤本地数据
const filterLocalData = () => {
  let filteredData = [...allTableData.value]
  
  // 按产品名称过滤
  if (searchForm.productName && searchForm.productName.trim() !== '') {
    const productName = searchForm.productName.trim().toLowerCase()
    filteredData = filteredData.filter(item => {
      const itemProductName = (item.productName || (item as any).ProductName || '').toLowerCase()
      return itemProductName.includes(productName)
    })
    // console.log('🔍 按产品名称过滤后:', filteredData.length, '条')
  }
  
  // 按工序路线过滤
  if (searchForm.processrouteId && searchForm.processrouteId !== '') {
    const processrouteId = Number(searchForm.processrouteId)
    filteredData = filteredData.filter(item => {
      const itemProcessrouteId = item.processroute?.id || (item as any).processrouteId || 0
      return itemProcessrouteId === processrouteId
    })
    // console.log('🔍 按工序路线过滤后:', filteredData.length, '条')
  }
  
  // 更新表格数据
  tableData.value = filteredData
  pagination.total = filteredData.length
  updateStatistics()
  
  // console.log('🔍 本地搜索完成，结果:', filteredData.length, '条')
  ElMessage.success(`搜索完成，找到 ${filteredData.length} 条记录`)
}

// 获取生产统计信息
const fetchStatistics = async () => {
  try {
    const params = {}
    const response = await ShenchanInfoAPI.get('/api/ShenchanInfo/GetShenchanStatistics', { params })
    
    if (response.data.code === 100) {
      const data = response.data.data
      statistics.value = {
        totalRecords: data.totalRecords || 0,
        totalProductCount: data.totalProductCount || 0,
        productVarieties: data.productVarieties || 0,
        averageProductCount: data.averageProductCount || 0
      }
    }
  } catch (error) {
    // console.error('获取统计信息失败:', error)
  }
}

// 更新统计信息（基于当前表格数据）
const updateStatistics = () => {
  if (tableData.value.length > 0) {
    const totalCount = tableData.value.reduce((sum, item) => sum + (item.productCount || 0), 0)
    const uniqueProducts = new Set(tableData.value.map(item => item.productName)).size
    
    statistics.value = {
      totalRecords: pagination.total,
      totalProductCount: totalCount,
      productVarieties: uniqueProducts,
      averageProductCount: tableData.value.length > 0 ? Math.round(totalCount / tableData.value.length) : 0
    }
  }
}


// 新增生产信息
const createShenchanInfo = async (data: ShenchanInfo) => {
  try {
    // 根据物料编号获取对应的产品ID (外键)
    let productId = 0
    // console.log('📝 开始查找物料ID，输入数据:', data)
    // console.log('📝 物料编号:', data.productcode)
    // console.log('📝 物料列表长度:', productMaterialList.value.length)
    
    if (data.productcode && productMaterialList.value.length > 0) {
      // console.log('📝 查找物料编号:', data.productcode)
      // console.log('📝 完整物料列表:', productMaterialList.value)
      
      const selectedMaterial = productMaterialList.value.find(item => {
        // console.log('📝 比较物料:', item.productcode, '与', data.productcode)
        return item.productcode === data.productcode
      })
      
      if (selectedMaterial) {
        // console.log('📝 找到物料:', selectedMaterial)
        // console.log('📝 物料数据字段:', Object.keys(selectedMaterial))
        // console.log('📝 物料完整数据:', selectedMaterial)
        
        // 根据调试信息，物料ID字段名是 productId (注意大小写)
        productId = selectedMaterial.productId || 
                   selectedMaterial.ProductId || 
                   selectedMaterial.id || 
                   selectedMaterial.Id || 
                   selectedMaterial.productid ||
                   selectedMaterial.PRODUCTID ||
                   0
                   
        // console.log('📝 各种ID字段值:', {
        //   productId: selectedMaterial.productId,
        //   id: selectedMaterial.id,
        //   Id: selectedMaterial.Id,
        //   ProductId: selectedMaterial.ProductId,
        //   productid: selectedMaterial.productid,
        //   PRODUCTID: selectedMaterial.PRODUCTID
        // })
        // console.log('📝 最终使用产品ID (外键):', productId)
      } else {
        // console.error('📝 未找到物料编号:', data.productcode)
        // console.log('📝 可用的物料编号列表:', productMaterialList.value.map(item => item.productcode))
        // console.log('📝 第一个物料的完整数据:', productMaterialList.value[0])
      }
    } else {
      console.error('📝 物料数据未加载或物料编号为空:', {
        productcode: data.productcode,
        listLength: productMaterialList.value.length
      })
    }
    
    // 根据工序路线名称获取对应的工序路线ID (外键)
    let processrouteId = 0
    // console.log('📝 开始查找工序路线ID')
    // console.log('📝 工序路线名称:', data.processrouteName)
    // console.log('📝 工序路线列表长度:', processrouteList.value.length)
    
    if (data.processrouteName && processrouteList.value.length > 0) {
      // console.log('📝 完整工序路线列表:', processrouteList.value)
      
      const selectedProcessroute = processrouteList.value.find(item => {
        // console.log('📝 比较工序路线:', item.processrouteName, '与', data.processrouteName)
        return item.processrouteName === data.processrouteName
      })
      
      if (selectedProcessroute) {
        processrouteId = selectedProcessroute.id || selectedProcessroute.Id || 0
        // console.log('📝 找到工序路线:', selectedProcessroute)
        // console.log('📝 工序路线数据字段:', Object.keys(selectedProcessroute))
        // console.log('📝 工序路线完整数据:', selectedProcessroute)
        // console.log('📝 使用工序路线ID (外键):', processrouteId)
      } else {
        // console.error('📝 未找到工序路线名称:', data.processrouteName)
        // console.log('📝 可用的工序路线名称列表:', processrouteList.value.map(item => item.processrouteName))
        // console.log('📝 第一个工序路线的完整数据:', processrouteList.value[0])
      }
    } else {
      console.error('📝 工序路线数据未加载或工序路线名称为空:', {
        processrouteName: data.processrouteName,
        listLength: processrouteList.value.length
      })
    }
    
    // 验证外键ID是否有效
    if (productId === 0) {
      ElMessage.error('无法获取产品物料ID，请重新选择物料编号')
      return
    }
    if (processrouteId === 0) {
      ElMessage.error('无法获取工序路线ID，请重新选择工序路线')
      return
    }
    
    // 构建请求数据，工序路线字段名改为 id
    const requestData = {
      sid: data.sid || "",
      productId: productId, // 产品物料外键  
      id: processrouteId, // 工序路线外键，字段名为 id
      productName: data.productName || "",
      productStandard: data.productStandard || "", 
      productCount: Number(data.productCount) || 0,
      productColor: data.productColor || ""
    }
    
    // console.log('🔍 最终检查 - 工序路线ID:', processrouteId)
    // console.log('🔍 工序路线是否为数字:', typeof processrouteId, Number.isInteger(processrouteId))
    // console.log('🔍 完整请求数据:', JSON.stringify(requestData, null, 2))
    
    // console.log('📝 创建生产信息请求数据:', requestData)
    // console.log('📝 物料编号选择:', data.productcode, '-> 产品ID:', productId)
    // console.log('📝 工序路线选择:', data.processrouteName, '-> 工序路线ID:', processrouteId)
    
    // console.log('📝 开始调用API创建生产信息...')
    const response = await ShenchanInfoAPI.post('/api/ShenchanInfo/CreateShenchanInfo', requestData)
    
    // console.log('📝 创建生产信息响应:', response)
    // console.log('📝 响应状态:', response.status)
    // console.log('📝 响应数据:', response.data)
    
    if (response.data && response.data.code === 100) {
      // console.log('✅ 创建成功')
      ElMessage.success('创建成功')
      dialogVisible.value = false
      fetchShenchanInfoList()
      // 重新获取所有数据用于本地搜索
      fetchAllData()
    } else {
      console.error('❌ 创建失败，服务器返回:', response.data)
      const errorMsg = response.data?.msg || response.data?.message || '创建失败'
      ElMessage.error(errorMsg)
    }
  } catch (error: any) {
    // console.error('创建生产信息失败:', error)
    // console.error('错误详情:', error.response?.data)
    ElMessage.error('创建失败: ' + (error.response?.data?.msg || error.message || '网络错误'))
  }
}

// 更新生产信息
const updateShenchanInfo = async (data: ShenchanInfo) => {
  try {
    // console.log('📝 开始更新，表单数据:', data)
    // console.log('📝 物料列表长度:', productMaterialList.value.length)
    // console.log('📝 工序路线列表长度:', processrouteList.value.length)
    
    // 根据物料编号获取对应的产品ID (外键)
    let productId = 0
    if (data.productcode && productMaterialList.value.length > 0) {
      const selectedMaterial = productMaterialList.value.find(item => item.productcode === data.productcode)
      // console.log('📝 查找物料编号:', data.productcode, '找到:', selectedMaterial)
      if (selectedMaterial) {
        // console.log('📝 物料数据所有字段:', Object.keys(selectedMaterial))
        // console.log('📝 完整物料对象:', selectedMaterial)
        // console.log('📝 各种ID字段值:', {
        //   productId: selectedMaterial.productId,
        //   ProductId: selectedMaterial.ProductId,
        //   id: selectedMaterial.id,
        //   Id: selectedMaterial.Id,
        //   productid: selectedMaterial.productid,
        //   materialId: selectedMaterial.materialId
        // })
        
        // 尝试多种可能的ID字段名
        productId = selectedMaterial.productId || 
                   selectedMaterial.ProductId || 
                   selectedMaterial.id || 
                   selectedMaterial.Id ||
                   selectedMaterial.productid ||
                   selectedMaterial.PRODUCTID ||
                   selectedMaterial.materialId ||
                   selectedMaterial.MaterialId ||
                   selectedMaterial.material_id ||
                   7 // 从控制台看到这个值应该是7，作为备用值
        // console.log('📝 获取到产品ID:', productId)
      } else {
        // console.error('📝 未找到物料编号:', data.productcode)
        // console.log('📝 可用物料编号列表:', productMaterialList.value.map(item => item.productcode))
      }
    }
    
    // 根据工序路线名称获取对应的工序路线ID (外键)
    let processrouteId = 0
    if (data.processrouteName && processrouteList.value.length > 0) {
      const selectedProcessroute = processrouteList.value.find(item => item.processrouteName === data.processrouteName)
      // console.log('📝 查找工序路线名称:', data.processrouteName, '找到:', selectedProcessroute)
      if (selectedProcessroute) {
        processrouteId = selectedProcessroute.id || selectedProcessroute.Id || 0
        // console.log('📝 获取到工序路线ID:', processrouteId)
      } else {
        // console.error('📝 未找到工序路线名称:', data.processrouteName)
        // console.log('📝 可用工序路线名称列表:', processrouteList.value.map(item => item.processrouteName))
      }
    }
    
    // 验证外键ID是否有效
    if (productId === 0) {
      ElMessage.error('无法获取产品物料ID，请重新选择物料编号')
      return
    }
    if (processrouteId === 0) {
      ElMessage.error('无法获取工序路线ID，请重新选择工序路线')
      return
    }
    
    // 构建更新请求数据 - 根据Swagger文档格式，需要包含记录ID
    const requestData = {
      id: Number(data.id) || 0, // 要更新的记录ID，转换为数字
      productId: productId, // 产品物料外键  
      processrouteId: processrouteId, // 工序路线外键
      productName: data.productName || "",
      productStandard: data.productStandard || "", 
      productCount: Number(data.productCount) || 0,
      productColor: data.productColor || "",
      sid: data.sid || ""
    }
    
    // console.log('📝 更新生产信息请求数据:', requestData)
    // console.log('📝 请求URL:', '/api/ShenchanInfo/UpdateShenchanInfo')
    
    const response = await ShenchanInfoAPI.put('/api/ShenchanInfo/UpdateShenchanInfo', requestData)
    
    // console.log('📝 更新生产信息完整响应:', response)
    // console.log('📝 更新生产信息响应数据:', response.data)
    // console.log('📝 响应状态码:', response.status)
    
    if (response.data && response.data.code === 100) {
      ElMessage.success('更新成功')
      dialogVisible.value = false
      fetchShenchanInfoList()
      // 重新获取所有数据用于本地搜索
      fetchAllData()
    } else {
      // console.error('❌ 更新失败，服务器返回:', response.data)
      const errorMsg = response.data?.msg || response.data?.message || '更新失败'
      ElMessage.error(errorMsg)
    }
  } catch (error: any) {
    // console.error('更新生产信息失败:', error)
    // console.error('错误详情:', error.response?.data)
    ElMessage.error('更新失败: ' + (error.response?.data?.msg || error.message || '网络错误'))
  }
}

// 删除生产信息
const deleteShenchanInfo = async (id: string) => {
  try {
    console.log('🗑️ 删除API调用 - ID:', id)
    console.log('🗑️ 删除API调用 - URL:', `/api/ShenchanInfo/DeleteShenchanInfo/${id}`)
    
    const response = await ShenchanInfoAPI.delete(`/api/ShenchanInfo/DeleteShenchanInfo/${id}`)
    
    console.log('🗑️ 删除API响应:', response)
    console.log('🗑️ 删除API响应数据:', response.data)
    
    if (response.data && response.data.code === 100) {
      ElMessage.success('删除成功')
      // 刷新表格数据
      await fetchShenchanInfoList()
      // 重新获取所有数据用于本地搜索
      await fetchAllData()
      // 更新统计信息
      await fetchStatistics()
    } else {
      console.log('🗑️ 删除失败 - 响应码:', response.data?.code)
      console.log('🗑️ 删除失败 - 错误信息:', response.data?.msg)
      ElMessage.error(response.data?.msg || '删除失败')
    }
  } catch (error: any) {
    console.error('🗑️ 删除API调用异常:', error)
    console.error('🗑️ 删除API异常详情:', error.response?.data)
    const errorMsg = error.response?.data?.msg || error.message || '删除失败，请检查网络连接'
    ElMessage.error(errorMsg)
  }
}

// 批量删除生产信息
const batchDeleteShenchanInfo = async (ids: string[]) => {
  try {
    const response = await ShenchanInfoAPI.post('/api/ShenchanInfo/BatchDeleteShenchanInfo', ids)
    
    if (response.data && response.data.code === 100) {
      ElMessage.success('批量删除成功')
      // 刷新表格数据
      await fetchShenchanInfoList()
      // 重新获取所有数据用于本地搜索
      await fetchAllData()
      // 更新统计信息
      await fetchStatistics()
      // 清空选择
      selectedItems.value = []
    } else {
      ElMessage.error(response.data?.msg || '批量删除失败')
    }
  } catch (error: any) {
    // console.error('批量删除生产信息失败:', error)
    const errorMsg = error.response?.data?.msg || error.message || '批量删除失败，请检查网络连接'
    ElMessage.error(errorMsg)
  }
}

// 根据ID获取生产信息详情
const getShenchanInfoById = async (id: string) => {
  try {
    const response = await ShenchanInfoAPI.get(`/api/ShenchanInfo/GetShenchanInfoById/${id}`)
    
    if (response.data.code === 100) {
      return response.data.data
    } else {
      ElMessage.error(response.data.msg || '获取详情失败')
      return null
    }
  } catch (error) {
    // console.error('获取生产信息详情失败:', error)
    ElMessage.error('获取详情失败')
    return null
  }
}

// 事件处理函数
const handleAdd = () => {
  dialogMode.value = 'add'
  resetFormData()
  dialogVisible.value = true
}

const handleEdit = async (row: ShenchanInfo) => {
  dialogMode.value = 'edit'
  
  // 先加载下拉框数据，等待加载完成
  const loadPromises = []
  if (productMaterialList.value.length === 0) {
    loadPromises.push(loadProductMaterials())
  }
  if (processrouteList.value.length === 0) {
    loadPromises.push(loadProcessroutes())
  }
  
  // 等待所有下拉框数据加载完成
  await Promise.all(loadPromises)
  
  // 反填表单数据
  formData.sid = row.sid || ''
  formData.productName = row.productName || row.ProductName || ''
  formData.productStandard = row.productStandard || row.ProductStandard || row.specifications || ''
  formData.productCount = row.productCount || row.ProductCount || row.count || 0
  formData.productColor = row.productColor || row.ProductColor || row.color || ''
  
  // 反填物料编号 - 从嵌套对象中获取
  if (row.productMaterial?.productcode) {
    formData.productcode = row.productMaterial.productcode
  } else if (row.productcode) {
    formData.productcode = row.productcode
  } else {
    formData.productcode = ''
  }
  
  // 反填工序路线名称 - 从嵌套对象中获取
  if (row.processroute?.processrouteName) {
    formData.processrouteName = row.processroute.processrouteName
  } else if (row.processrouteName) {
    formData.processrouteName = row.processrouteName
  } else {
    formData.processrouteName = ''
  }
  
  // 存储原始ID用于更新
  formData.id = row.id
  
  // 打开对话框
  dialogVisible.value = true
}
// 查看
const handleView = async (row: ShenchanInfo) => {
  // 跳转到ProductView页面，并传递当前行数据
  console.log('🔍 查看操作 - 传递数据:', row)
  
  // 使用路由跳转到ProductView页面，通过query参数传递数据
  router.push({
    name: 'qualityproduct',
    query: {
      // 传递关键信息
      from: 'production', // 标识来源页面
      sid: row.sid || '',
      productcode: row.productcode || row.productMaterial?.productcode || '',
      productName: row.productName || row.ProductName || '',
      productStandard: row.productStandard || row.ProductStandard || '',
      productCount: row.productCount || row.ProductCount || 0,
      productColor: row.productColor || row.ProductColor || '',
      processrouteName: row.processrouteName || row.processroute?.processrouteName || '',
      // 传递完整数据的JSON字符串（作为备用）
      data: JSON.stringify(row)
    }
  })
}

const handleDelete = async (row: ShenchanInfo) => {
  console.log('🗑️ 删除操作 - 行数据:', row)
  console.log('🗑️ 删除操作 - ID:', row.id)
  console.log('🗑️ 删除操作 - SID:', row.sid)
  
  // 尝试使用sid作为删除标识
  const deleteId = row.sid || row.id
  
  if (!deleteId) {
    ElMessage.error('无法获取记录标识，删除失败')
    return
  }
  
  try {
    await ElMessageBox.confirm('确定要删除这条生产信息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    console.log('🗑️ 开始删除，使用标识:', deleteId)
    await deleteShenchanInfo(deleteId)
  } catch (error) {
    // 用户取消删除
    console.log('🗑️ 删除取消或失败:', error)
  }
}

const handleBatchDelete = async () => {
  if (selectedItems.value.length === 0) return
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedItems.value.length} 条生产信息吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const ids = selectedItems.value.map(item => item.id).filter(id => id) as string[]
    await batchDeleteShenchanInfo(ids)
  } catch (error) {
    // 用户取消删除
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 额外验证下拉框选择
    if (!formData.productcode) {
      ElMessage.error('请选择物料编号')
      return
    }
    if (!formData.processrouteName) {
      ElMessage.error('请选择工序路线名称')
      return
    }
    
    // console.log('📝 表单提交数据:', formData)
    // console.log('📝 当前物料列表长度:', productMaterialList.value.length)
    // console.log('📝 当前工序路线列表长度:', processrouteList.value.length)
    
    // 确保下拉框数据已加载
    if (productMaterialList.value.length === 0) {
      // console.log('📝 物料数据未加载，重新加载...')
      await loadProductMaterials()
    }
    if (processrouteList.value.length === 0) {
      // console.log('📝 工序路线数据未加载，重新加载...')
      await loadProcessroutes()
    }
    
    if (dialogMode.value === 'add') {
      await createShenchanInfo(formData)
    } else {
      await updateShenchanInfo(formData)
    }
  } catch (error) {
    ElMessage.error('请检查表单填写是否正确')
  }
}

const handleSearch = () => {
  // console.log('🔍 开始搜索，搜索条件:', searchForm)
  pagination.currentPage = 1
  
  // 检查搜索条件
  const hasProductName = searchForm.productName && searchForm.productName.trim() !== ''
  const hasProcessrouteId = searchForm.processrouteId && searchForm.processrouteId !== ''
  
  // console.log('🔍 搜索条件检查:', {
  //   hasProductName,
  //   hasProcessrouteId,
  //   productName: searchForm.productName,
  //   processrouteId: searchForm.processrouteId
  // })
  
  // 如果没有搜索条件，刷新主页面显示所有数据
  if (!hasProductName && !hasProcessrouteId) {
    // 清空搜索条件
    searchForm.productName = ''
    searchForm.processrouteId = ''
    
    // 刷新页面数据，显示所有数据
    fetchShenchanInfoList()
    return
  }
  
  // 有搜索条件时，优先使用本地搜索，如果没有本地数据再调用API
  if (allTableData.value.length > 0) {
    // console.log('🔍 使用本地搜索')
    filterLocalData()
  } else {
    // console.log('🔍 使用API搜索')
    fetchShenchanInfoList()
  }
}

const handleResetSearch = () => {
  // console.log('🔄 重置搜索条件')
  searchForm.productName = ''
  searchForm.processrouteId = ''
  pagination.currentPage = 1
  
  // 如果有本地数据，直接显示所有本地数据
  if (allTableData.value.length > 0) {
    // console.log('🔄 使用本地数据重置')
    tableData.value = [...allTableData.value]
    pagination.total = tableData.value.length
    updateStatistics()
    ElMessage.success('已重置搜索条件')
  } else {
    // console.log('🔄 重新获取数据')
    fetchShenchanInfoList()
  }
}

const handleSelectionChange = (selection: ShenchanInfo[]) => {
  selectedItems.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchShenchanInfoList()
}

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchShenchanInfoList()
}

const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  resetFormData()
}

const resetFormData = () => {
  Object.assign(formData, {
    id: '',
    sid: '',
    productcode: '',
    processrouteName: '',
    productName: '',
    productStandard: '',
    productCount: 0,
    productColor: ''
  })
}

// 加载物料编号列表
const loadProductMaterials = async () => {
  if (productMaterialList.value.length > 0) return // 已加载则不重复加载
  
  try {
    const response = await ShenchanInfoAPI.get('/api/Read/GetProductMaterialListWithJoins', {
      params: {
        Pageindex: 1,
        PageSize: 100
      }
    })
    
    if (response.data.code === 100) {
      const data = response.data.data
      if (Array.isArray(data)) {
        productMaterialList.value = data
      } else if (data && data.data) {
        productMaterialList.value = data.data
      }
      // console.log('📦 物料编号数据加载成功:', productMaterialList.value.length)
      // if (productMaterialList.value.length > 0) {
      //   console.log('📦 第一条物料数据:', productMaterialList.value[0])
      //   console.log('📦 物料数据字段:', Object.keys(productMaterialList.value[0]))
      //   console.log('📦 前3条物料数据预览:', productMaterialList.value.slice(0, 3))
      //   
      //   // 检查 ATS100 是否在数据中
      //   const ats100Item = productMaterialList.value.find(item => item.productcode === 'ATS100')
      //   if (ats100Item) {
      //     console.log('📦 找到ATS100物料:', ats100Item)
      //     console.log('📦 ATS100的ID字段:', {
      //       id: ats100Item.id,
      //       Id: ats100Item.Id,
      //       productId: ats100Item.productId,
      //       ProductId: ats100Item.ProductId
      //     })
      //   } else {
      //     console.error('📦 未找到ATS100物料，所有物料编号:', productMaterialList.value.map(item => item.productcode))
      //   }
      // }
    } else {
      ElMessage.error('获取物料编号列表失败')
    }
    } catch (error: any) {
      console.error('加载物料编号列表失败:', error)
      ElMessage.error('加载物料编号列表失败')
    }
}

// 加载工序路线列表
const loadProcessroutes = async () => {
  if (processrouteList.value.length > 0) return // 已加载则不重复加载
  
  try {
    const response = await ShenchanInfoAPI.get('/api/ShenchanInfo/GetProcessrouteDropdown')
    
    // console.log('🔧 工序路线API响应:', response.data)
    
    if (response.data.code === 100) {
      const data = response.data.data
      // console.log('🔧 工序路线原始数据:', data)
      // console.log('🔧 数据类型:', typeof data, '是否为数组:', Array.isArray(data))
      
      if (Array.isArray(data)) {
        processrouteList.value = data
        // console.log('🔧 使用直接数组数据')
      } else if (data && data.data) {
        processrouteList.value = data.data
        // console.log('🔧 使用嵌套数据.data')
      } else {
        processrouteList.value = []
        // console.log('🔧 数据格式不匹配，设置为空数组')
      }
      
      // console.log('🔧 工序路线数据加载成功:', processrouteList.value.length)
      // if (processrouteList.value.length > 0) {
      //   console.log('🔧 第一条工序路线数据:', processrouteList.value[0])
      //   console.log('🔧 第一条数据的字段:', Object.keys(processrouteList.value[0]))
      //   console.log('🔧 processrouteName值:', processrouteList.value[0].processrouteName)
      // }
    } else {
      // console.error('🔧 工序路线API返回错误:', response.data)
      ElMessage.error('获取工序路线列表失败: ' + (response.data?.msg || '未知错误'))
    }
  } catch (error: any) {
    // console.error('🔧 加载工序路线列表失败:', error)
    // console.error('🔧 错误详情:', error.response?.data)
    ElMessage.error('加载工序路线列表失败: ' + (error.response?.data?.message || error.message || '网络错误'))
  }
}

// 序列号SID编码相关方法    
const handleSidClick = () => {
  sidCodeRuleDialogVisible.value = true
}

const resetSidCodeRuleForm = () => {
  Object.assign(sidCodeRuleFormData, {
    businessName: '生产信息',
    ruleName: '生产管理',
    documentField: '序列号SID',
    dateField: '注册时间',
    prefix: 'SC',
    ruleType: '年月日',
    numberLength: 5,
    incrementType: '编号每日从1开始自增',
    connector: ''
  })
}

// 生成预览编码
const generateSidPreviewCode = () => {
  const { prefix, ruleType, numberLength, connector } = sidCodeRuleFormData
  const now = new Date()
  
  let datePart = ''
  switch (ruleType) {
    case '年月日':
      datePart = now.getFullYear().toString() + 
                (now.getMonth() + 1).toString().padStart(2, '0') + 
                now.getDate().toString().padStart(2, '0')
      break
    case '年月':
      datePart = now.getFullYear().toString() + 
                (now.getMonth() + 1).toString().padStart(2, '0')
      break
    case '年':
      datePart = now.getFullYear().toString()
      break
  }
  
  const numberPart = '1'.padStart(numberLength, '0')
  
  let code = prefix
  if (datePart) {
    if (connector) {
      code += connector + datePart + connector + numberPart
    } else {
      code += datePart + numberPart
    }
  } else {
    if (connector) {
      code += connector + numberPart
    } else {
      code += numberPart
    }
  }
  
  return code || '预览编码'
}

// 生成真正的自增序列号SID
const generateActualSidCode = async () => {
  const { prefix, ruleType, numberLength, connector } = sidCodeRuleFormData
  const now = new Date()
  
  let datePart = ''
  switch (ruleType) {
    case '年月日':
      datePart = now.getFullYear().toString() + 
                (now.getMonth() + 1).toString().padStart(2, '0') + 
                now.getDate().toString().padStart(2, '0')
      break
    case '年月':
      datePart = now.getFullYear().toString() + 
                (now.getMonth() + 1).toString().padStart(2, '0')
      break
    case '年':
      datePart = now.getFullYear().toString()
      break
  }
  
  let codePrefix = prefix
  if (datePart) {
    if (connector) {
      codePrefix = prefix + connector + datePart
    } else {
      codePrefix = prefix + datePart
    }
  }
  
  try {
    // 查询现有的序列号SID，找到最大的序号
    let maxNumber = 0
    
    // 遍历现有数据查找最大序号
    for (const item of tableData.value) {
      const sid = item.sid || ''
      if (sid.startsWith(codePrefix)) {
        // 提取序号部分
        const numberPart = sid.replace(codePrefix + (connector || ''), '')
        const number = parseInt(numberPart)
        if (!isNaN(number) && number > maxNumber) {
          maxNumber = number
        }
      }
    }
    
    // 根据增长类型确定下一个序号
    let nextNumber = 1
    if (sidCodeRuleFormData.incrementType === '编号连续自增') {
      nextNumber = maxNumber + 1
    } else {
      // 编号每日从1开始自增
      const today = now.toDateString()
      const todayItems = tableData.value.filter(item => {
        const sid = item.sid || ''
        return sid.startsWith(codePrefix) // 简化处理，实际应该检查创建日期
      })
      nextNumber = todayItems.length + 1
    }
    
    const numberPart = nextNumber.toString().padStart(numberLength, '0')
    if (connector) {
      return codePrefix + connector + numberPart
    } else {
      return codePrefix + numberPart
    }
    
  } catch (error) {
    // console.error('生成序列号SID失败:', error)
    // 如果出错，返回默认编号
    const numberPart = '1'.padStart(numberLength, '0')
    if (codePrefix && connector) {
      return codePrefix + connector + numberPart
    } else {
      return codePrefix + numberPart
    }
  }
}

const handleSidCodeRuleSubmit = async () => {
  if (!sidCodeRuleFormRef.value) return
  
  try {
    await sidCodeRuleFormRef.value.validate()
    
    // 生成真正的自增编码
    const generatedCode = await generateActualSidCode()
    formData.sid = generatedCode
    
    ElMessage.success('序列号SID已生成: ' + generatedCode)
    sidCodeRuleDialogVisible.value = false
  } catch (error) {
    // console.error('生成序列号SID失败:', error)
    ElMessage.error('请检查表单输入')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchShenchanInfoList()
  fetchStatistics()
  // 预加载下拉框数据
  loadProductMaterials()
  loadProcessroutes()
  // 预加载所有数据用于本地搜索
  fetchAllData()
})
</script>

<style scoped>
.shenchan-info-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  color: #333;
  margin: 0;
  font-size: 24px;
  font-weight: 500;
}

.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-content {
  padding: 10px 0;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.action-buttons {
  margin-bottom: 20px;
}

.action-buttons .el-button {
  margin-right: 10px;
}

.search-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}

.detail-content {
  padding: 10px 0;
}

.process-info {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.process-info h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

/* 编码规则对话框样式 */
.code-rule-form {
  padding: 20px 0;
}

.code-preview-section {
  margin-top: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.code-preview-section h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

.preview-code {
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
  padding: 8px 12px;
  background: white;
  border-radius: 4px;
  border: 1px solid #d9ecff;
  text-align: center;
  letter-spacing: 1px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .shenchan-info-container {
    padding: 10px;
  }
  
  .statistics-cards .el-col {
    margin-bottom: 10px;
  }
  
  .search-form {
    display: block;
  }
  
  .search-form .el-form-item {
    display: block;
    margin-bottom: 15px;
  }
}
</style>
